<template>
  <div>
    TrendParams
    <el-button type="primary" size="mini" @click="handleClickAdd" :disabled="disabled">添加属性</el-button>

    <el-table border stripe :data="list">
      <el-table-column type="expand">
        <template slot-scope="scoped">
          <el-tag
            v-for="(item,index) in scoped.row.attr_vals"
            :key="item"
            closable
            style="margin-right:10px;"
            @close="closeTag(index,scoped.row)"
          >{{item}}</el-tag>
          <el-input
            class="input-new-tag"
            v-if="scoped.row.inputVisible"
            v-model="scoped.row.inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm(scoped.row)"
            @blur="handleInputConfirm(scoped.row)"
          ></el-input>
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput(scoped.row)"
          >+ New Tag</el-button>
        </template>
      </el-table-column>
      <el-table-column type="index"></el-table-column>
      <el-table-column label="属性名称" prop="attr_name"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scoped">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleEdit(scoped.row.attr_id)"
          >编辑</el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDelete(scoped.row.attr_id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 对话框 -->
    <el-dialog title="添加属性" :visible.sync="isAddVisible" width="50%" @close="handleAddDialog">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="属性名称" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog title="修改" :visible.sync="isEditVisible" width="50%" @close="handleEditDialog">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    disabled: Boolean,
    params: Object
  },
  data() {
    return {
      list: [],
      isAddVisible: false,
      isEditVisible: false,
      addForm: {
        attr_name: ''
      },
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '不能为空,请输入!', trigger: 'blur' }
        ]
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '不能为空,请输入!', trigger: 'blur' }
        ]
      },
      inputVisible: false,
      inputValue: ''
    }
  },
  methods: {
    handleClickAdd() {
      this.isAddVisible = true
    },
    async getList() {
      const { data: res } = await this.$http.get(
        `categories/${this.params.id}/attributes`,
        {
          params: { sel: this.params.sel }
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      this.list = res.data
      console.log(this.list)
    },
    handleAddDialog() {
      this.$refs.addFormRef.resetFields()
    },
    handleEditDialog() {
      this.$refs.editFormRef.resetFields()
    },
    handleAddConfirm() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.params.id}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: 'only'
          }
        )
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        console.log(res)
      })
      this.getList()
      this.isAddVisible = false
    },
    handleEditConfirm() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.params.id}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: 'only'
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        console.log(res)
      })
      this.getList()
      this.isEditVisible = false
    },
    async handleEdit(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.params.id}/attributes/${attr_id}`,
        {
          params: { attr_sel: 'only' }
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.editForm = res.data
      this.isEditVisible = true
    },
    async handleDelete(attr_id) {
      const comfirmRes = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (comfirmRes !== 'confirm') {
        return this.$message.info('已取消删除!')
      }

      const { data: res } = await this.$http.delete(
        `categories/${this.params.id}/attributes/${attr_id}`,
        {
          params: { attr_sel: 'only' }
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getList()
    },
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveTag(row)
    },
    showInput(row) {
      row.inputVisible = true
      //$nextTick当页面上元素被重新渲染之后
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    closeTag(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveTag(row)
    },
    async saveTag(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.params.id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    }
  },
  watch: {
    params: function() {
      console.log(this.params)
      this.getList()
    }
  },
  created() {
    console.log(this.disabled)
    console.log(this.params)
    this.getList()
  }
}
</script>

<style lang="less" scoped>
.input-new-tag {
  width: 120px;
}
</style>